package com.jack.tang.juc.demos;



public class communicate {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.plus();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.minor();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();
    }
}

class Data {
    private int number = 0;

    //如果number=0,则number+1
    public synchronized void plus() throws InterruptedException {
        if (number != 0)
            this.wait();//等待
        number++;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        this.notifyAll();//唤醒其他线程
    }

    //如果number!=0,则number-1
    public synchronized void minor() throws InterruptedException {
        if (number == 0)
            this.wait();
        number--;
        System.out.println(Thread.currentThread().getName() + "=>" + number);
        this.notifyAll();//唤醒其他线程
    }
}
